package com.cn.provider.mq;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 接收消息，即消费者
 */
@Component
public class MqReceiver {

    private static Logger logger = LoggerFactory.getLogger(MqReceiver.class);
    @RabbitListener(bindings = @QueueBinding(
            /**
             * durable=true,交换机持久化,rabbitmq服务重启交换机依然存在,保证不丢失; durable=false,相反
             * auto-delete=true:无消费者时，队列自动删除; auto-delete=false：无消费者时，队列不会自动删除排他性，
             * exclusive=true:首次申明的connection连接下可见; exclusive=false：所有connection连接下不可见
            */
            value = @Queue(value = "${spring.rabbitmq.custom.testQueue}", durable = "true", autoDelete = "false",
                    exclusive = "false"),
            exchange = @Exchange("${spring.rabbitmq.custom.testExchange}"),
            key = "routeKey"
    ))
    public void testQueue(String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) {
        try {
            logger.info(message);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicAck(-1, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }
}
